package org.springframework.samples.mvc.fileupload;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.activation.MimetypesFileTypeMap;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mvc.extensions.ajax.AjaxUtils;
import org.springframework.samples.mvc.service.ImageService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.WebRequest;

@Controller
@RequestMapping("/download")
public class FileDownloadController {
	
	int BUFFER_LENGTH = 4096;
	
	@Autowired
	private ServletContext servletContext;
	
	/*
	 * ImageView는 파일 시스템에 있는 이미지 파일을 응답으로 돌려주는 역할을 합니다.
	 * 뒷 부분에서 ImageView 클래스를 작성하게 됩니다.
	 */
	@Resource(name="imageView") 
	ImageView imageView;
	
	@Autowired 
	ImageService imageService;
	
	@ModelAttribute
	public void ajaxAttribute(WebRequest request, Model model) {
		model.addAttribute("ajaxRequest", AjaxUtils.isAjaxRequest(request));
	}

	@RequestMapping(method=RequestMethod.GET)
	public void fileUploadForm(@RequestParam("fileName") String fileName) {
		System.out.println("★★★★★ step 1 - download");
        String fullPath = "C:/images/" + fileName ;
        File downloadFile = new File(fullPath);
//        downloads(fullPath, fullPath, downloadFile, null, null, null); 
	}
 

	  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	 
	    String filePath = request.getRequestURI();
	 
	    File file = new File(System.getenv("OPENSHIFT_DATA_DIR") + filePath.replace("/uploads/",""));
	    InputStream input = new FileInputStream(file);
	 
	    response.setContentLength((int) file.length());
	    response.setContentType(new MimetypesFileTypeMap().getContentType(file));
	 
	    OutputStream output = response.getOutputStream();
	    byte[] bytes = new byte[BUFFER_LENGTH];
	    int read = 0;
	    while ((read = input.read(bytes, 0, BUFFER_LENGTH)) != -1) {
	        output.write(bytes, 0, read);
	        output.flush();
	    }
	 
	    input.close();
	    output.close();
	  }

	@RequestMapping("/image/{imageId}")
	private ImageView getImage(@PathVariable String imageId, ModelMap modelMap) {
		ImageFile imageFile = imageService.get(imageId);
		
		modelMap.put("imageFile", imageFile);
		
		return imageView;
	}
	@RequestMapping("download")
	private ImageView downloads(@RequestParam("key")String key,@RequestParam("path")String path, File file, ModelMap modelMap,HttpServletRequest req,HttpServletResponse res) {
		

        res.setContentType("applicaiton/download;charset=utf-8");
		
		
		String fullPath = path +File.separator + key;
		System.out.println("★★★★★  fullPath=="+fullPath);
		String userAgent = req.getHeader("User-Agent");
		String originalFileName="한글 .png";

		
		try {

	        String fileName = URLEncoder.encode(originalFileName, "UTF-8");
			if (userAgent.indexOf("MSIE 5.5") > -1) { // MS IE 5.5 이하
				res.setHeader("Content-Disposition", "filename=" + fileName.replaceAll("\\+", "\\ ") + ";");
			} else if (userAgent.indexOf("MSIE") > -1) { // MS IE (보통은 6.x 이상 가정)
				res.setHeader("Content-Disposition", "attachment; filename=" + fileName.replaceAll("\\+", "\\ ") + ";");
			} else if (userAgent.indexOf("Trident") > -1) { // MS IE 11
				res.setHeader("Content-Disposition", "attachment; filename=" + fileName.replaceAll("\\+", "\\ ") + ";");
			} else { // 모질라나 오페라
				res.setHeader("Content-Disposition", "attachment; filename=" + new String(originalFileName.getBytes("euc-kr"), "latin1").replaceAll("\\+", "\\ ") + ";");
			}
			res.setHeader("Content-Transfer-Encoding", "binary");

			OutputStream out = res.getOutputStream();
	        FileInputStream fis = null;
	        fis = new FileInputStream(file);
	        FileCopyUtils.copy(fis, out);
	        
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		
        
        
        
        
		return imageView;
	}
	 
	
	
}
